
package com.wangzha.business.ctrl;

import com.jfinal.aop.Inject;
import com.jfinal.core.Path;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;
import com.wangzha.business.service.*;
import com.wangzha.common.base.BaseController;
import com.wangzha.common.model.Record_recordGroup;
import com.wangzha.common.model.UserRecordGroup;
import com.wangzha.common.model.UserRecordParam;
import com.wangzha.common.model.UserUploadFile;
import com.wangzha.common.oss.OSSProvider;
import com.wangzha.common.response.R;
import com.wangzha.common.vo.Grid;
import com.wangzha.portal.core.service.SysUserService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import java.io.File;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Path("/user/upload/file")
public class UserUploadFileController extends BaseController {

    private static final Logger LOG = Logger.getLogger(UserUploadFileController.class);

    @Inject
    DeviceGroupService deviceGroupService;

    @Inject
    SysUserService sysUserService;

    @Inject
    UserUploadFileService userUploadFileService;

    @Inject
    OSSProvider ossProvider;

    @Inject
    UserRecordGroupService userRecordGroupService;

    @Inject
    Record_recordGroupService record_recordGroupService;

    @Inject
    UserRecordParamService userRecordParamService;

//    public void list() {
//        Record record = getAllParamsToRecord();
//        record.remove("pageSize","pageNumber");
//        renderJson(recordGroupService.queryForList(getParaToInt("pageNumber",1), getParaToInt("pageSize",10), record, "order by id desc"));
//    }



    public void list() {
        Record record = new Record();
        record.set("user_code", getVisitor().getCode());
        Grid grid = userUploadFileService.queryForListEq(getParaToInt("pageNumber", 1),
                getParaToInt("pageSize", 10), record);
        if (grid != null) {
            List<Record> records = (List<Record>) grid.getList();
            if (CollectionUtils.isNotEmpty(records)) {
               for (Record r : records) {
                   if (StringUtils.isNotBlank(r.getStr("name"))) {
                       r.set("name", r.getStr("name").split("_")[0]);
                   }
               }
            }
            grid.setList(records);
        }
        renderJson(grid);
    }

    public void listByGroupId() {
        if (StringUtils.isEmpty(getPara("groupId"))) {
            renderJson(new Grid());
            return;
        }
        Record record = new Record();
        record.set("user_code", getVisitor().getCode());
        UserRecordGroup userRecordGroup = (UserRecordGroup) userRecordGroupService.findById(getPara("groupId"));

        List<UserRecordParam> userRecordParamList = userRecordParamService.findUserRecordParam(getVisitor().getCode(), getLong("groupId"));
        Map<Long, UserRecordParam> userRecordParamMap = userRecordParamList.stream()
                .collect(Collectors.toMap(UserRecordParam::getRecordId, Function.identity()));

        List<Record_recordGroup> record_recordGroupList = record_recordGroupService.findByGroupId(userRecordGroup.getParentGroupId());
        List<String> recordIds = record_recordGroupList.stream().map(Record_recordGroup :: getRecordId)
                .map(x -> String.valueOf(x)).collect(Collectors.toList());
        Grid grid = userUploadFileService.queryByIds(getParaToInt("pageNumber", 1),
                getParaToInt("pageSize", 10), recordIds);
        if (CollectionUtils.isNotEmpty(grid.getList())) {
            for (Record r : (List<Record>)grid.getList()) {
               UserRecordParam userRecordParam = userRecordParamMap.get(r.getLong("id"));
               if (userRecordParam != null) {
                   r.set("extra_params", userRecordParam.getExtraParams());
                   r.set("run_time", userRecordParam.getRunTime());
                   r.set("polling_interval", userRecordParam.getPollingInterval());
                   r.set("action_interval", userRecordParam.getActionInterval());
               } else {
                   r.set("extra_params", "请点击修改话术");
                   r.set("run_time", null);
               }
            }
        }
        renderJson(grid);
    }

    public void add() {
        if ("index".equals(getPara("pageName"))) {
            render("index.html");
        } else if ("distribute".equals(getPara("pageName"))) {
            render("distribute.html");
        } else if ("file_view".equals(getPara("pageName"))) {
            setAttr("id", getParaToInt("id"));
            render("file_view.html");
        } else {
            render("add.html");
        }
    }

    public void save() {
        UserUploadFile entity = getBean(UserUploadFile.class);
        entity.save();
        setAttr("userUploadFile", entity);
        render("add.html");
    }

    public void edit() {
        setAttr("userUploadFile", userUploadFileService.findById(getPara(0)));
        render("edit.html");
    }

    public void uploadFile() {
        UploadFile up = getFile();
        Integer id = getParaToInt("id");
        if (up == null || id == null || id == 0) {
            renderJson(fail("上传失败"));
            return;
        } else {
            UserUploadFile userUploadFile = (UserUploadFile)userUploadFileService.findById(id + "");
            if (userUploadFile == null || StringUtils.isBlank(userUploadFile.getIdentifier())) {
                renderJson(fail("上传失败"));
            } else {
                String url = ossProvider.putObject(up.getFile(), userUploadFile.getIdentifier());
                userUploadFile.setUrl(url).update();
                renderJson(fail("上传成功"));
            }
            File file = new File(up.getUploadPath() + "/" + up.getOriginalFileName());
            file.delete();
            return;
        }

    }

    public void update() {
        UserUploadFile entity = getBean(UserUploadFile.class);
        entity.update();
        setAttr("userUploadFile", entity);
        render("edit.html");
    }

    public void delete() {
        userUploadFileService.deleteByIds(getIds());
        renderJson(suc());
    }

    /**
     * 表单修改字段值
     */
    public void updateFieldValue(){
        getModel(UserUploadFile.class).update();
        renderJson(suc("修改成功"));
    }


    /**
     * 配置角色用户页面
     */
    public void destribute(){
        setAttr("groupIds", getPara("groupIds"));
        render("distribute_user.html");
    }

    /**
     * 分发
     */
    public void saveDestribute(){
        try {

            String groupIds = getPara("groupIds");
            String userCodes = getPara("userCodes");
            if (StringUtils.isBlank(groupIds) || StringUtils.isBlank(userCodes)) {
                renderJson(R.fail("分发失败"));
                return;
            }
            String[] groupIdArr = groupIds.split(",");
            String[] userCodeArr = userCodes.split(",");
            List<UserRecordGroup> recordGroupList = (List<UserRecordGroup>) userRecordGroupService.findByIds(Arrays.asList(groupIdArr));
            if (CollectionUtils.isNotEmpty(recordGroupList)) {
                List<UserRecordGroup> userRecordGroupList = new ArrayList<>();
                for (UserRecordGroup userRecordGroup : recordGroupList) {
                    for (String userCode : userCodeArr) {
                        UserRecordGroup temp = new UserRecordGroup();
                        temp.setUserCode(userCode);
                        temp.setName(userRecordGroup.getName());
                        temp.setParentGroupId(userRecordGroup.getParentGroupId());
                        temp.setCreateTime(new Date());
                        temp.setUpdateTime(new Date());
                        userRecordGroupList.add(temp);
                    }
                }
                userRecordGroupService.saveUserRecordGroups(userRecordGroupList);
            }
        } catch(Exception e) {
            LOG.error(e.getMessage(), e);
            renderJson(fail("分发成功"));
            return;
        }
        renderJson(suc("分发成功"));
    }

    /**
     * 查询角色用户列表
     */
//    public void queryRoleUserList(){
//        int pageNumber=getParaToInt("pageNumber",1);
//        int pageSize=getParaToInt("pageSize",10);
//
//        Grid grid=sysUserRoleService.queryRoleUserList(pageNumber, pageSize,roleCode,record);
//        renderJson(grid);
//    }

    /**
     * 查询角色未选的用户列表
     */
//    public void queryUserListNotInRoleCode(){
//        int pageNumber=getParaToInt("pageNumber",1);
//        int pageSize=getParaToInt("pageSize",10);
//        String roleCode=getPara("roleCode");
//
//        Record record=new Record();
//        record.set("userName", getPara("userName"));
//        record.set("orgId", getPara("orgId"));
//
//        Grid grid=sysUserRoleService.queryUserListNotInRoleCode(pageNumber, pageSize,roleCode,record);
//        renderJson(grid);
//    }

    /**
     * 移除角色用户
     */
//    public void deleteRoleUser(){
//        boolean b=sysUserRoleService.deleteRoleUser(getPara("userCode"), getPara("roleCode"));
//        renderJson(suc(b?"移除成功":"移除失败"));
//    }

}

